<?php

namespace App\BO\Product;

use App\Entities\ProductEntity;
use App\Entities\ProductModel;
use App\Exceptions\Product\ProductNotFoundException;
use App\Models\ProductRange;
use App\Utils\Assert;

class ProductBOFactory
{
    /**
     * @param int $productId
     * @param int $cityId
     * @return ProductBO
     * @throws \Exception
     */
    public static function getByProductIdAndCityId(int $productId, int $cityId)
    {
        $bo = new ProductBO();

        $baseEntity = ProductEntity::find($productId);
        Assert::notNull($baseEntity, new ProductNotFoundException($productId));

        $bo->setBaseProductInfo($baseEntity);

        $cityProduct = null;
        if ($cityId != 0) {
            $pids = ProductRange::getCityProductIds($cityId);
            if (!in_array($productId, $pids)) {
                return null;
            }
            $cityProduct = ProductModel::where('product_pid', $productId)
                ->where('product_city', $cityId)
                ->where('product_open_city_config', 1)    // 是否启用城市单独配置
                ->first();
        }

        if (is_null($cityProduct)) {  // 没有单独配置城市
            $bo->setCityProductInfo($baseEntity);
        } else {
            $bo->setCityProductInfo(new ProductEntity($cityProduct));
        }

        return $bo;
    }
}
